import 'dart:async';
import 'dart:developer';

import '../../index.dart';
import '../widgets/filter/filter_button.dart';

class TodoPage extends StatefulWidget {
  const TodoPage({Key? key}) : super(key: key);

  @override
  _TodoState createState() => _TodoState();
}

class _TodoState extends State<TodoPage> {
  final List<String> _tabs = <String>['待处理', '已处理', '抄送我', '已提交'];
  List<FilterSelectData> selectList = [];

  @override
  Widget build(BuildContext context) {
    // return Scaffold(
    //     appBar: AppBar(
    //     title: Text("工单详情"),));
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: DefaultTabController(
          length: _tabs.length,
          child: Scaffold(
            appBar: AppBar(
              title: const Text("我的待办"),
              centerTitle: true,
              bottom: TabBar(
                indicatorColor: Theme.of(context).primaryColor,
                labelColor: Theme.of(context).primaryColor,
                unselectedLabelColor:
                    Theme.of(context).colorScheme.onBackground,
                tabs: _tabs.map((String name) => Tab(text: name)).toList(),
              ),
              // actions: [
              //   FutureBuilder(
              //       future: DefaultAssetBundle.of(context)
              //           .loadString('load_jsons/todo_filter.json'),
              //       builder: (futureBuilderContext, snapshot) {
              //         if (snapshot.connectionState != ConnectionState.done) {
              //           return Container();
              //         }
              //         return FilterButton(
              //           initConfigJson: snapshot.data.toString(),
              //           // onInit: (List<FilterSelectData> selectList) {
              //           //   setState(() {
              //           //     this.selectList = selectList;
              //           //     childState.currentState?.refresh(selectList);
              //           //   });
              //           // },
              //           onSelect: (List<FilterSelectData> selectList) {
              //             //选中回调
              //             Debug.info(">>>>>选中回调<<<<<");
              //             this.selectList = selectList;
              //             eventBus.fire(SelectEvent(selectList));
              //           },
              //         );
              //       })
              //
              //   // TextButton(child: Text("筛选"), onPressed: () {}),
              // ],
            ),
            body: TabBarView(
              children: _tabs.map((String name) {
                return Builder(
                  builder: (BuildContext context) {
                    return _buildTabView(name);
                  },
                );
              }).toList(),
            ), // 构建主页面
          ),
        ),
      ),
    );
  }

  Widget _buildTabView(String name) {
    return _TodoListPage(
      type: _tabs.indexOf(name),
      selectList: selectList,
    );
  }
}

class _TodoListPage extends StatefulWidget {
  late int type;
  List<FilterSelectData> selectList;

  _TodoListPage({Key? key, this.type = 0, required this.selectList})
      : super(key: key);

  @override
  _TodoListState createState() => _TodoListState();
}

class _TodoListState extends State<_TodoListPage> {
  final EasyRefreshController _controller = EasyRefreshController();
  final PageData<Todo> _pageData = PageData<Todo>();
  late StreamSubscription orderSubscription;
  late StreamSubscription selectSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _handlerRefresh();
    orderSubscription = eventBus.on<OrderEvent>().listen((event) {
      _handlerRefresh();
    });
    selectSubscription = eventBus.on<SelectEvent>().listen((event) {
      setState(() {
        widget.selectList = event.selectList;
        _controller.callRefresh();
        // _pageData.loadStatus = LoadStatus.loading;
        // _pageData.items.clear();
        //
        // //第一次不显示加载框 其它时候加载
        // _handlerRefresh();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    Debug.info("取消订阅");
    //取消订阅
    orderSubscription.cancel();
    selectSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      header: LightHeader(),
      footer: LightFooter(),
      emptyWidget:
          _pageData.items.isEmpty ? HintWidget(pageData: _pageData) : null,
      controller: _controller,
      onRefresh: () => _handlerRefresh(),
      onLoad: () => _handlerRefresh(refresh: false),
      child: ListView.separated(
        itemCount: _pageData.items.length,
        itemBuilder: (context, index) {
          return TodoItem(widget.type, _pageData.items[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return const Divider(
            endIndent: 16,
            height: 1,
          );
        },
      ),
    );
    // : HintWidget(pageData: _pageData);
  }

  Future _handlerRefresh({bool refresh = true}) async {
    try {
      _pageData.loadStatus = LoadStatus.loading;

      Map<String, dynamic> queryParameters;
      if (refresh) {
        queryParameters = _pageData.newQueryParameters();
        for (FilterSelectData selectData in widget.selectList) {
          queryParameters.addAll({selectData.code: selectData.valueString()});
        }
      } else {
        queryParameters = _pageData.moreQueryParameters();
      }

      ResponseData<RecordData<Todo>> responseData = await Api(context)
          .getListTodo(
              type: widget.type,
              queryParameters: queryParameters,
              refresh: refresh);
      if (responseData.success) {
        RecordData<Todo> recordData = responseData.dataModel!;
        List<Todo> todos = recordData.recordModels;
        //如果返回的数据小于指定的条数，则表示没有更多数据，反之则否
        //把请求到的新数据添加到items中
        if (mounted) {
          setState(() {
            _pageData.loadStatus = LoadStatus.loadSuccess;
            _pageData.current = recordData.current as int;
            if (_pageData.current == PageData.initCurrent) {
              //第一页
              _pageData.items.clear();
            }
            _pageData.items.addAll(todos.map((e) => e));
            if (_pageData.items.length == recordData.total as int) {
              //没有更多
              _controller.finishLoad(noMore: true);
            } else {
              _controller.finishLoad(noMore: false);
            }
          });
        }
      } else {
        _pageData.hint = responseData.msg;
        //请求失败
        showToast(responseData.msg);
        setState(() {
          _pageData.loadStatus = LoadStatus.loadFail;
        });
      }
    } on DioError catch (e) {
      //登录失败则提示
      _pageData.hint = e.response?.statusMessage ?? S.of(context).networkError;
      _pageData.code = e.response?.statusCode;
      _pageData.errorType = e.type;
      if (_pageData.items.isNotEmpty) {
        showToast(e.response?.statusMessage ?? S.of(context).networkError);
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } on Error catch (e) {
      //登录失败则提示
      _pageData.hint =
          Global.isRelease ? S.of(context).networkError : e.toString();
      if (_pageData.items.isNotEmpty) {
        showToast(Global.isRelease ? S.of(context).networkError : e.toString());
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } finally {}
  }
}
